package com.my.bbs.controller.rest;

import com.my.bbs.common.Constants;
import com.my.bbs.entity.MyPost;
import com.my.bbs.entity.MyPostCategory;
import com.my.bbs.entity.MyRole;
import com.my.bbs.entity.MyUser;
import com.my.bbs.service.*;
import com.my.bbs.util.PageQueryUtil;
import com.my.bbs.util.PageResult;
import com.my.bbs.util.Result;
import com.my.bbs.util.ResultGenerator;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 86187
 */
@Controller
public class MyPostController {
    @Resource
    private MyPostService myPostService;
    @Resource
    private MyPostCategoryService myPostCategoryService;
    @Resource
    private MyUserService myUserService;
    @Resource
    private MyPostCollectService myPostCollectService;
    @Resource
    private MyPostCommentService myPostCommentService;
    @Resource
    private MyRoleService roleService;

    @GetMapping("detail/{postId}")
    public String postDetail(HttpServletRequest request, @PathVariable(value = "postId") Long postId,
                             @RequestParam(value = "commentPage", required = false, defaultValue = "1") Integer commentPage) {
        List<MyPostCategory> myPostCategories = myPostCategoryService.getMyPostCategories();
        if (CollectionUtils.isEmpty(myPostCategories)) {
            return "error/error_404";
        }
        //将分类数据封装到request域中
        request.setAttribute("myPostCategories", myPostCategories);

        // 帖子内容
        MyPost myPost = myPostService.getMyPostForDetail(postId);
        if (myPost == null) {
            return "error/error_404";
        }
        request.setAttribute("myPost", myPost);
        // 发帖用户信息
        MyUser myUser = myUserService.getUserById(myPost.getPublishUserId());
        if (myUser == null) {
            return "error/error_404";
        }
        request.setAttribute("postUser", myUser);
        HttpSession session = request.getSession();
        request.setAttribute(Constants.USER_SESSION_KEY, session.getAttribute(Constants.USER_SESSION_KEY));

        // 是否收藏了本贴
        MyUser currentUser = (MyUser) request.getSession().getAttribute(Constants.USER_SESSION_KEY);
        request.setAttribute("currentUserCollectFlag", myPostCollectService.validUserCollect(currentUser.getUserId(), postId));

        // 本周热议的帖子
        request.setAttribute("hotTopicMyPostList", myPostService.getHotTopicMyPostList());

        // 人气用户图表信息
        List<MyUser> hotUsers = myUserService.getSumViews();
        List<String> nickNames = hotUsers.stream().map(i -> i.getNickName()).collect(Collectors.toList());
        List<Long> sumViews = hotUsers.stream().map(i -> i.getSumViews()).collect(Collectors.toList());
        request.setAttribute("nickNames", nickNames);
        request.setAttribute("sumViews", sumViews);
        // 当前用户角色
        MyRole role = (MyRole) session.getAttribute(Constants.USER_ROLE);
        request.setAttribute(Constants.USER_ROLE, role);

        // 帖子用户角色
        MyRole pageUserRole = roleService.getCodeById(myUser.getRoleId());
        request.setAttribute("pageUserRole", pageUserRole);

        // 评论数据
        PageResult commentsPage = myPostCommentService.getCommentsByPostId(postId, commentPage);
        request.setAttribute("commentsPage", commentsPage);

        return "jie/detail";
    }

    @GetMapping("editPostPage/{postId}")
    public String editPostPage(HttpServletRequest request, @PathVariable(value = "postId") Long postId) {
        MyUser myUser = (MyUser) request.getSession().getAttribute(Constants.USER_SESSION_KEY);
        List<MyPostCategory> myPostCategories = myPostCategoryService.getMyPostCategories();
        if (CollectionUtils.isEmpty(myPostCategories)) {
            return "error/error_404";
        }
        //将分类数据封装到request域中
        request.setAttribute("myPostCategories", myPostCategories);
        if (null == postId || postId < 0) {
            return "error/error_404";
        }
        MyPost myPost = myPostService.getMyPostById(postId);
        if (myPost == null) {
            return "error/error_404";
        }
        if (!myUser.getUserId().equals(myPost.getPublishUserId())) {
            request.setAttribute("message", "非本人发帖，无权限修改");
            return "error/error";
        }
        request.setAttribute("myPost", myPost);
        request.setAttribute("postId", postId);
        return "jie/edit";
    }

    @GetMapping("/addPostPage")
    public String addPostPage(HttpServletRequest request) {
        List<MyPostCategory> myPostCategories = myPostCategoryService.getMyPostCategories();
        if (CollectionUtils.isEmpty(myPostCategories)) {
            return "error/error_404";
        }
        //将分类数据封装到request域中
        request.setAttribute("myPostCategories", myPostCategories);
        return "jie/add";
    }

    @PostMapping("/addPost")
    @ResponseBody
    public Result addPost(MyPost post, HttpSession httpSession) {

        // 帖子标题
        String postTitle = post.getPostTitle();

        // 帖子类别
        Integer postCategoryId = post.getPostCategoryId();

        // 帖子详情
        String postContent = post.getPostContent();

        MyPostCategory myPostCategory = myPostCategoryService.selectById(postCategoryId);
        MyUser myUser = (MyUser) httpSession.getAttribute(Constants.USER_SESSION_KEY);
        MyPost myPost = new MyPost();
        myPost.setPublishUserId(myUser.getUserId());
        myPost.setPostTitle(postTitle);
        myPost.setPostContent(postContent);
        myPost.setPostCategoryId(postCategoryId);
        myPost.setPostCategoryName(myPostCategory.getCategoryName());
        if (myPostService.savePost(myPost) > 0) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("请求失败，请检查参数及账号是否有操作权限");
        }
    }

    @PostMapping("/delPost/{postId}")
    @ResponseBody
    public Result delPost(@PathVariable("postId") Long postId,
                          HttpSession httpSession) {
        if (null == postId || postId < 0) {
            return ResultGenerator.genFailResult("postId参数错误");
        }
        MyUser myUser = (MyUser) httpSession.getAttribute(Constants.USER_SESSION_KEY);
        if (myPostService.delMyPost(myUser.getUserId(), postId) > 0) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("请求失败，请检查参数及账号是否有操作权限");
        }
    }

    @PostMapping("/editPost")
    @ResponseBody
    public Result editPost(MyPost post, HttpSession httpSession) {
        MyUser myUser = (MyUser) httpSession.getAttribute(Constants.USER_SESSION_KEY);

        MyPostCategory myPostCategory = myPostCategoryService.selectById(post.getPostCategoryId());
        post.setPostCategoryName(myPostCategory.getCategoryName());
        post.setLastUpdateTime(new Date());
        post.setPublishUserId(myUser.getUserId());
        if (myPostService.updateMyPost(post) > 0) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("请求失败，请检查参数及账号是否有操作权限");
        }
    }

    @PostMapping("/postBanned")
    @ResponseBody
    public Result postBanned(MyPost post){
        post.setPostStatus((byte)2);
        int i = myPostService.bannedPost(post);
        if(i > 0){
            return ResultGenerator.genSuccessResult();
        }
        return ResultGenerator.genFailResult("封禁失败");
    }

    @PostMapping("/postUnBanned")
    @ResponseBody
    public Result postUnBanned(MyPost post){
        post.setPostStatus((byte)1);
        return myPostService.unbannedPost(post);
    }

    @GetMapping("/getBannedPost")
    public String getBannedPost(HttpServletRequest request,
                                @RequestParam(value = "page", required = false, defaultValue = "1") Integer pageNumber,
                                @RequestParam(value = "keyword", required = false) String keyword){
        //封装参数
        Map<String, Object> params = new HashMap<>(5);
        params.put("page", pageNumber);
        //默认每页10条
        params.put("limit", 10);

        //搜索关键字
        if (StringUtils.hasLength(keyword)) {
            request.setAttribute("keyword", keyword);
            params.put("keyword", keyword);
        }

        PageQueryUtil pageUtil = new PageQueryUtil(params);
        PageResult pageBannedUser = myPostService.getPageBannedPost(pageUtil);

        request.setAttribute("pageResult", pageBannedUser);
        return "admin/postBlackHome";
    }
}
